Creating, Accessing, and Updating Lists in Python
Course: Python Programming
Topic: Creating, Accessing, and Updating Lists
Course Link: Python Training Course
Demo Link: Register for a Course Demo
JustAcademy Homepage: Visit JustAcademy
1. Introduction to Python Lists
A list is a built-in Python data structure used to store multiple items in a single variable. Lists are useful when a program needs to manage a collection of related values, such as student names, product prices, employee records, or daily temperatures.
Python lists are ordered, mutable, and allow duplicate values. They can contain values of the same type or different types.
Example
student_names = ["Amit", "Priya", "Rahul"]
marks = [85, 92, 78, 92]
mixed_data = ["Python", 25, 89.5, True]
print(student_names)
print(marks)
print(mixed_data)
Output
['Amit', 'Priya', 'Rahul']
[85, 92, 78, 92]
['Python', 25, 89.5, True]
Important Characteristics of Lists
| Characteristic |
Description |
Example |
| Ordered |
Items maintain their sequence. |
[10, 20, 30] |
| Mutable |
Items can be changed after creation. |
numbers[0] = 99 |
| Duplicates allowed |
The same value can appear more than once. |
[5, 5, 10] |
| Mixed data types |
A list can store different types of objects. |
["A", 10, True] |
| Indexed |
Each item can be accessed using its position. |
numbers[0] |
| Resizable |
Items can be added or removed. |
numbers.append(40) |
2. Creating Lists in Python
Lists are generally created by placing comma-separated values inside square brackets []. Python also provides the list() constructor for creating lists from iterable objects.
2.1 Creating a List of Strings
fruits = ["Apple", "Banana", "Mango"]
print(fruits)
Output:
['Apple', 'Banana', 'Mango']
2.2 Creating a List of Numbers
prices = [120, 250, 180, 300]
print(prices)
Output:
[120, 250, 180, 300]
2.3 Creating an Empty List
An empty list contains no elements. It is useful when the program will collect or generate values later.
tasks = []
print(tasks)
print(len(tasks))
Output:
[]
0
2.4 Creating a List with Different Data Types
employee = ["Neha", 28, 45000.50, True]
print(employee)
Output:
['Neha', 28, 45000.5, True]
Although mixed-type lists are allowed, lists containing values with a common purpose are often easier to understand and process.
2.5 Creating a List with the list() Constructor
The list() constructor converts an iterable, such as a string or tuple, into a list.
letters = list("PYTHON")
print(letters)
values = list((10, 20, 30))
print(values)
Output:
['P', 'Y', 'T', 'H', 'O', 'N']
[10, 20, 30]
When a string is passed to list(), each character becomes a separate element.
2.6 Creating a List with Repeated Values
The repetition operator * can create a list containing repeated values.
zeros = [0] * 5
print(zeros)
labels = ["Pending"] * 3
print(labels)
Output:
[0, 0, 0, 0, 0]
['Pending', 'Pending', 'Pending']
Note: Repeating immutable values such as numbers and strings is straightforward. Repeating a mutable object such as a nested list can create multiple references to the same inner object.
3. Understanding List Indexing
Indexing is used to access an individual element of a list. Python uses zero-based indexing, which means the first element is at index 0, the second at index 1, and so on.
Example
languages = ["Python", "Java", "JavaScript", "SQL"]
print(languages[0])
print(languages[1])
print(languages[2])
print(languages[3])
Output:
Python
Java
JavaScript
SQL
Positive Indexing
| Element |
Index |
| Python |
0 |
| Java |
1 |
| JavaScript |
2 |
| SQL |
3 |
Negative Indexing
Negative indexing accesses elements from the end of a list. The last item has index -1, the second-last has index -2, and so on.
languages = ["Python", "Java", "JavaScript", "SQL"]
print(languages[-1])
print(languages[-2])
print(languages[-3])
Output:
SQL
JavaScript
Java
Accessing the First and Last Elements
numbers = [12, 24, 36, 48, 60]
first_item = numbers[0]
last_item = numbers[-1]
print("First:", first_item)
print("Last:", last_item)
Output:
First: 12
Last: 60
4. Accessing List Elements Using Slicing
Slicing extracts a range of elements and returns a new list. Its general syntax is:
list_name[start:stop:step]
- start: Index where the slice begins; included in the result.
- stop: Index where the slice ends; excluded from the result.
- step: Number of positions to move between selected elements. The default is
1.
Example 1: Basic Slicing
numbers = [10, 20, 30, 40, 50, 60]
print(numbers[1:4])
print(numbers[0:3])
print(numbers[2:])
Output:
[20, 30, 40]
[10, 20, 30]
[30, 40, 50, 60]
Example 2: Slicing with a Step
numbers = [10, 20, 30, 40, 50, 60]
print(numbers[::2])
print(numbers[1::2])
Output:
[10, 30, 50]
[20, 40, 60]
Example 3: Reversing a List with Slicing
numbers = [1, 2, 3, 4, 5]
reversed_numbers = numbers[::-1]
print(reversed_numbers)
Output:
[5, 4, 3, 2, 1]
Slicing is useful for selecting a subset of records, processing a range of values, or creating a shallow copy of a list. Unlike indexing, slicing generally handles out-of-range boundaries without raising an IndexError.
5. Updating List Elements
Python lists are mutable, meaning their elements can be changed after the list is created. You can update a single element through its index or replace several elements using slice assignment.
5.1 Updating an Element by Index
colors = ["Red", "Blue", "Green"]
colors[1] = "Yellow"
print(colors)
Output:
['Red', 'Yellow', 'Green']
The element at index 1 changes from "Blue" to "Yellow". The list's length remains the same.
5.2 Updating an Element Using a Negative Index
scores = [65, 70, 80, 90]
scores[-1] = 95
print(scores)
Output:
[65, 70, 80, 95]
5.3 Updating Multiple Elements with Slice Assignment
Slice assignment replaces a range of elements. The replacement list can contain a different number of elements, so the list's length may change.
letters = ["a", "b", "c", "d", "e"]
letters[1:4] = ["B", "C", "D"]
print(letters)
Output:
['a', 'B', 'C', 'D', 'e']
5.4 Replacing a Range with Fewer Elements
numbers = [10, 20, 30, 40, 50]
numbers[1:4] = [99]
print(numbers)
Output:
[10, 99, 50]
The three elements selected by numbers[1:4] are replaced by one element. Therefore, the resulting list becomes shorter.
5.5 Replacing a Range with More Elements
numbers = [10, 20, 30, 40]
numbers[1:2] = [15, 18, 20]
print(numbers)
Output:
[10, 15, 18, 20, 30, 40]
Slice assignment can insert multiple elements while replacing a selected range. If the slice is empty, it can also be used to insert values at a position.
6. Adding New Elements to a List
Python provides several methods for adding elements. The appropriate method depends on whether you want to add one element, insert an element at a particular position, or add multiple elements.
6.1 Using append()
The append() method adds one item to the end of a list.
fruits = ["Apple", "Banana"]
fruits.append("Mango")
print(fruits)
Output:
['Apple', 'Banana', 'Mango']
Important: append() adds its argument as one element. If the argument is a list, that list becomes a nested element.
numbers = [1, 2, 3]
numbers.append([4, 5])
print(numbers)
Output:
[1, 2, 3, [4, 5]]
6.2 Using insert()
The insert() method adds an element at a specified index.
fruits = ["Apple", "Mango"]
fruits.insert(1, "Banana")
print(fruits)
Output:
['Apple', 'Banana', 'Mango']
The existing elements at and after the insertion position shift to the right.
6.3 Using extend()
The extend() method adds each element from an iterable to the end of the existing list.
numbers = [1, 2, 3]
numbers.extend([4, 5, 6])
print(numbers)
Output:
[1, 2, 3, 4, 5, 6]
Difference Between append(), insert(), and extend()
| Method |
Purpose |
Example |
Result |
append() |
Adds one item at the end. |
a.append([3, 4]) |
[1, 2, [3, 4]] |
insert() |
Adds one item at a chosen index. |
a.insert(1, 9) |
[1, 9, 2] |
extend() |
Adds each item from an iterable. |
a.extend([3, 4]) |
[1, 2, 3, 4] |
7. Removing Elements from a List
Updating a list also includes deleting unwanted elements. Python offers methods and statements for removing elements by value, by position, or by range.
7.1 Using remove()
The remove() method removes the first occurrence of a specified value. It raises a ValueError if the value is not found.
fruits = ["Apple", "Banana", "Mango", "Banana"]
fruits.remove("Banana")
print(fruits)
Output:
['Apple', 'Mango', 'Banana']
7.2 Using pop()
The pop() method removes and returns an element. If no index is provided, it removes the last element.
numbers = [10, 20, 30, 40]
removed_item = numbers.pop(1)
print("Removed:", removed_item)
print("Updated list:", numbers)
Output:
Removed: 20
Updated list: [10, 30, 40]
7.3 Using del
The del statement deletes an element by index, a range of elements, or all elements in a list.
numbers = [10, 20, 30, 40, 50]
del numbers[1]
print(numbers)
del numbers[1:3]
print(numbers)
Output:
[10, 30, 40, 50]
[10, 50]
7.4 Using clear()
The clear() method removes all elements while keeping the list object available.
tasks = ["Study", "Practice", "Revise"]
tasks.clear()
print(tasks)
Output:
[]
Comparison of Removal Techniques
| Operation |
Removes By |
Returns Removed Value? |
remove(value) |
Value |
No |
pop(index) |
Index |
Yes |
del list[index] |
Index or slice |
No |
clear() |
All elements |
No |
8. Accessing List Elements with Loops
Loops make it possible to process every element in a list without manually writing an index for each item.
8.1 Using a for Loop
subjects = ["Python", "SQL", "Power BI"]
for subject in subjects:
print(subject)
Output:
Python
SQL
Power BI
8.2 Using range() and Indexing
prices = [100, 200, 300]
for index in range(len(prices)):
print(index, prices[index])
Output:
0 100
1 200
2 300
8.3 Using enumerate()
The enumerate() function provides both the index and the corresponding value while iterating over a list.
students = ["Asha", "Ravi", "Karan"]
for index, student in enumerate(students):
print(index, student)
Output:
0 Asha
1 Ravi
2 Karan
Use enumerate() when both positions and values are needed. Avoid modifying the size of a list while iterating over it, because removing or inserting elements during iteration can cause elements to be skipped or processed unexpectedly.
9. Checking Whether an Item Exists
The in operator checks whether a value exists in a list. The not in operator checks whether it does not exist.
available_courses = ["Python", "Java", "SQL"]
print("Python" in available_courses)
print("C++" in available_courses)
print("C++" not in available_courses)
Output:
True
False
True
Membership checks are useful for validating user choices, verifying available products, and avoiding attempts to remove values that do not exist.
Safe Removal Example
items = ["Pen", "Book", "Pencil"]
item_to_remove = "Eraser"
if item_to_remove in items:
items.remove(item_to_remove)
else:
print("Item not found")
print(items)
Output:
Item not found
['Pen', 'Book', 'Pencil']
10. Finding the Length and Basic Information of a List
The built-in len() function returns the number of elements in a list. Other built-in functions can calculate basic information from lists containing suitable values.
marks = [78, 85, 92, 88]
print("Number of marks:", len(marks))
print("Highest mark:", max(marks))
print("Lowest mark:", min(marks))
print("Total marks:", sum(marks))
Output:
Number of marks: 4
Highest mark: 92
Lowest mark: 78
Total marks: 343
Note: max(), min(), and sum() require compatible values. For example, sum() cannot directly add a list containing strings and numbers.
11. Combining Lists
Lists can be combined using the + operator. The operator creates a new list containing the elements of both lists.
morning_tasks = ["Read", "Exercise"]
evening_tasks = ["Practice", "Revise"]
all_tasks = morning_tasks + evening_tasks
print(all_tasks)
print(morning_tasks)
Output:
['Read', 'Exercise', 'Practice', 'Revise']
['Read', 'Exercise']
The original lists remain unchanged when using + to create a new list. To add items to an existing list, use methods such as extend() or the += operator.
12. Copying Lists and Understanding References
Assigning one list variable to another does not create a separate list. Both names refer to the same list object. As a result, modifying the list through either variable affects the same underlying data.
12.1 Assignment Creates Another Reference
original = [10, 20, 30]
alias = original
alias[0] = 99
print("Original:", original)
print("Alias:", alias)
Output:
Original: [99, 20, 30]
Alias: [99, 20, 30]
12.2 Creating a Shallow Copy with copy()
Use the copy() method or slicing to create a shallow copy of a list. Changes to the top-level elements of one list will not change the corresponding elements of the other list. However, nested mutable objects are still shared by a shallow copy.
original = [10, 20, 30]
copied = original.copy()
copied[0] = 99
print("Original:", original)
print("Copied:", copied)
Output:
Original: [10, 20, 30]
Copied: [99, 20, 30]
12.3 Copying with Slicing
original = ["A", "B", "C"]
copied = original[:]
copied.append("D")
print(original)
print(copied)
Output:
['A', 'B', 'C']
['A', 'B', 'C', 'D']
For deeply nested data where independent copies of nested objects are required, Python's copy module provides deepcopy().
13. Sorting and Reversing Lists
Lists can be rearranged using the sort() and reverse() methods. Both methods modify the existing list in place.
13.1 Using sort()
numbers = [40, 10, 30, 20]
numbers.sort()
print(numbers)
numbers.sort(reverse=True)
print(numbers)
Output:
[10, 20, 30, 40]
[40, 30, 20, 10]
13.2 Using reverse()
letters = ["A", "B", "C", "D"]
letters.reverse()
print(letters)
Output:
['D', 'C', 'B', 'A']
Sorting arranges elements according to their ordering, while reversing simply changes their current order. These operations are not interchangeable.
14. Nested Lists
A nested list is a list that contains one or more lists as elements. Nested lists are useful for representing tables, matrices, grids, or grouped records.
Example
students = [
["Asha", 85],
["Ravi", 90],
["Karan", 78]
]
print(students[0])
print(students[0][0])
print(students[1][1])
Output:
['Asha', 85]
Asha
90
students[0] accesses the first inner list. students[0][0] accesses the first element inside that inner list.
Updating a Nested List
students = [
["Asha", 85],
["Ravi", 90]
]
students[0][1] = 95
print(students)
Output:
[['Asha', 95], ['Ravi', 90]]
15. Practical Example: Managing a Shopping List
This example demonstrates how to create, access, update, add, and remove items from a list in a realistic situation.
shopping_list = ["Milk", "Bread", "Eggs"]
# Display the initial list
print("Initial shopping list:", shopping_list)
# Access an item
print("First item:", shopping_list[0])
# Update an item
shopping_list[1] = "Whole Wheat Bread"
# Add a new item
shopping_list.append("Apples")
# Insert an item at the beginning
shopping_list.insert(0, "Rice")
# Remove an item
shopping_list.remove("Eggs")
# Display the final list
print("Updated shopping list:", shopping_list)
print("Total items:", len(shopping_list))
Output
Initial shopping list: ['Milk', 'Bread', 'Eggs']
First item: Milk
Updated shopping list: ['Rice', 'Milk', 'Whole Wheat Bread', 'Apples']
Total items: 4
Explanation
- The list is initialized with three shopping items.
- Index
0 is used to access the first item.
- Index
1 is updated with a different bread type.
append() adds apples to the end.
insert() adds rice at the beginning.
remove() deletes eggs by value.
len() counts the remaining items.
16. Common List Errors and How to Avoid Them
| Error or Issue |
Why It Happens |
How to Fix It |
IndexError |
Accessing an index that does not exist. |
Check the list length and valid index range. |
ValueError with remove() |
The requested value is not present. |
Check membership with in first. |
| Unexpected nested list |
Using append() with a list when individual items were intended. |
Use extend() for adding its individual elements. |
| Unexpected shared changes |
Assigning one list variable to another. |
Use copy() or slicing for a shallow copy. |
| Incorrect list update |
Using an index outside the existing list's valid range. |
Assign to an existing index or use an insertion method. |
| Unexpected loop behavior |
Adding or removing elements while iterating over the same list. |
Iterate over a copy or build a new list. |
Printing None |
Printing the result of in-place methods such as append() or sort(). |
Call the method first, then print the list separately. |
Example: Avoiding an IndexError
numbers = [10, 20, 30]
index = 3
if 0 <= index < len(numbers):
print(numbers[index])
else:
print("Invalid index")
Output:
Invalid index
Example: Understanding append() Return Values
numbers = [1, 2, 3]
result = numbers.append(4)
print(result)
print(numbers)
Output:
None
[1, 2, 3, 4]
The list changes in place, but append() returns None. Do not assign its return value when you intend to keep the updated list.
17. Best Practices for Working with Lists
- Use descriptive names such as
student_names, product_prices, or pending_tasks.
- Use indexing when accessing a specific element and slicing when selecting a range.
- Choose
append(), insert(), or extend() based on the required operation.
- Validate indexes and values before accessing or removing elements when input is uncertain.
- Use
enumerate() when a loop needs both index and value.
- Use
copy() or slicing when a separate top-level list is needed.
- Do not modify a list's size while directly iterating over it unless the behavior is carefully controlled.
- Use lists for ordered collections that may change; consider tuples for fixed sequences that should not be modified.
- For frequent insertion or removal at the beginning of a sequence, consider
collections.deque instead of a list.
- Keep list contents consistent where practical, especially when calculations or sorting are required.
18. Practice Exercises
Beginner Exercises
- Create a list containing five favorite foods and print it.
- Create a list of six numbers and print the first and last elements.
- Use negative indexing to display the last two elements of a list.
- Create a list of programming languages and update one item.
- Add a new element to the end of a list using
append().
Intermediate Exercises
- Create a list of ten numbers and display the elements from index
2 through index 6.
- Insert an item at index
2 using insert().
- Use
extend() to combine two lists without creating a separate result list.
- Remove an element by value and another by index.
- Sort a list of numbers in ascending and descending order.
- Create a copy of a list and demonstrate that updating the copy does not change the original list's top-level elements.
Advanced Exercises
- Create a nested list containing student names and marks. Update one student's marks.
- Write a program that checks whether a requested product exists before removing it.
- Write a program that finds the highest, lowest, and average marks in a numeric list.
- Use
enumerate() to display each task with its position.
- Write a program that replaces a selected range of list elements using slice assignment.
19. Mini Project: Student Marks Manager
Project Objective: Build a small Python program that stores student marks in a list and allows the user to view, update, add, and remove marks.
Project Code
marks = [78, 85, 92, 67]
print("Current marks:", marks)
# Access a mark
print("First student's mark:", marks[0])
# Update a mark
marks[1] = 88
print("After updating:", marks)
# Add a new mark
marks.append(90)
print("After adding:", marks)
# Insert a mark at a specific position
marks.insert(2, 75)
print("After inserting:", marks)
# Remove a mark by value
if 67 in marks:
marks.remove(67)
print("After removing:", marks)
# Display statistics
print("Number of students:", len(marks))
print("Highest mark:", max(marks))
print("Lowest mark:", min(marks))
print("Total marks:", sum(marks))
print("Average marks:", sum(marks) / len(marks))
Expected Output
Current marks: [78, 85, 92, 67]
First student's mark: 78
After updating: [78, 88, 92, 67]
After adding: [78, 88, 92, 67, 90]
After inserting: [78, 88, 75, 92, 67, 90]
After removing: [78, 88, 75, 92, 90]
Number of students: 5
Highest mark: 92
Lowest mark: 75
Total marks: 423
Average marks: 84.6
Project Extension Tasks
- Accept marks from the user using
input().
- Validate that each mark falls within the range of 0 to 100.
- Display marks with their student positions using
enumerate().
- Allow the user to select which index should be updated.
- Display the list in ascending order without losing the original order.
20. Interview Questions and Answers
Q1. What is a list in Python?
A list is an ordered, mutable collection that can store multiple elements, including duplicate values and values of different data types.
Q2. How do you create a list?
Use square brackets, for example, numbers = [10, 20, 30], or use the list() constructor with an iterable.
Q3. What is the difference between positive and negative indexing?
Positive indexing starts at 0 from the beginning. Negative indexing starts at -1 from the end.
Q4. How can you update an element in a list?
Assign a new value to an existing index, such as numbers[1] = 50.
Q5. What is the difference between append() and extend()?
append() adds its argument as one element, whereas extend() adds each element from an iterable.
Q6. What is the difference between remove() and pop()?
remove() deletes the first matching value and returns nothing. pop() removes an element by index and returns that element; without an index, it removes the last element.
Q7. What is list slicing?
Slicing selects a range of elements using syntax such as numbers[1:4]. The starting index is included, and the stopping index is excluded.
Q8. Are Python lists mutable?
Yes. List elements can be replaced, added, or removed after the list has been created.
Q9. How do you create a copy of a list?
Use numbers.copy() or numbers[:] to create a shallow copy.
Q10. What happens when you assign one list to another variable?
Both variables refer to the same list object. Changes made through one variable are visible through the other.
Q11. How do you check whether a value exists in a list?
Use the in operator, for example, if "Python" in languages:.
Q12. How do you remove all elements from a list?
Use list_name.clear(). This empties the existing list object without deleting the variable itself.
21. Quick Revision Checklist
- A list is written using square brackets:
[].
- Lists are ordered, mutable, and allow duplicates.
- Positive indexing starts at
0; negative indexing starts at -1.
- Slicing follows the pattern
list[start:stop:step].
- Use
append() to add one item at the end.
- Use
insert() to add an item at a specified index.
- Use
extend() to add elements from an iterable.
- Use
remove() to delete by value and pop() to delete by index.
- Use
del to delete an element or a range, and clear() to empty the list.
- Use
len() to count elements and enumerate() to loop with indexes.
- Use
copy() or slicing for a shallow copy rather than simple assignment.
- Remember that in-place methods such as
append(), sort(), and reverse() modify the original list and generally return None.
22. Conclusion
Creating, accessing, and updating lists is an essential Python programming skill. Lists allow developers to store collections of values, retrieve elements through indexing and slicing, update existing values, add new items, remove unwanted data, and process collections using loops.
Practicing list operations with everyday examples such as student marks, shopping items, and task managers helps build a strong foundation for more advanced topics, including functions, list comprehensions, nested data structures, and data processing.
Explore more learning resources and course information through the links below: